//
//  WZDayPlanController.m
//  ETong
//
//  Created by wanzhao on 15/10/29.
//  Copyright (c) 2016年 wanzhao. All rights reserved.
//

#import "WZDayPlanController.h"
#import "VRGCalendarView.h"
#import "WZDayPlan.h"
#import "WZDayPlanCell.h"
#import "WZAddScheduleController.h"
#import "WZNavigationController.h"
#import "WZDetailSceduleController.h"
#import "KMDatePicker.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CAccountModel.h"
#import "NSString+MyString.h"
#import "NSString+fish_MD5.h"
#import "NSDate+convenience.h"
#import "WZScheduleList.h"
#import "JKAlertDialog.h"
#import "LBCalendar.h"
#import "LBStarView.h"
#import "DateSelectView.h"


// 日历
#define KCalendar_TitleView_Height 50
#define KCalendar_WeekDayView_Height 40
#define KCalendar_contentView_Height 300
#define KCalendar_Spacing 5
#define KCalendar_ChangeView_Height 44

#define KScreen_Height [UIScreen mainScreen].bounds.size.height
#define KScreen_width [UIScreen mainScreen].bounds.size.width

#define DayPlan_DeleteSchedule_Remind @"确定删除该日程吗?"



// 日程
#define LocalNotification_Userinfo_KEY @"scheduleTitle"
#define DayPlan_GetSchedule_MonthInfo  @""
#define WZNetWorking_Remind            @"加载中..."
#define Notification_UserInfo_Key      @"DayPlanCount"

@interface WZDayPlanController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, ChangeBGScrollviewAlphaDelegate, WZAddScheduleControllerDelegate, KMDatePickerDelegate>

{
    DateSelectView * dsView;
}



@property (nonatomic, strong) CContactModel *curAccount;
@property (nonatomic, strong) CAccountModel *acc;
@property (nonatomic, strong) VRGCalendarView *calendar1;
@property (nonatomic, strong) WZDayPlan *dayPlan;

// 日历
//@property (nonatomic, weak) LBCalendarContentView *calendarContentView;
//@property (nonatomic, weak) UIScrollView *BGScrollview;
//@property (nonatomic, strong) DateSelectView *dsView;
@property (nonatomic, weak) UIView *changeView;
@property (nonatomic, weak) UIButton *changeButton;
@property (nonatomic, weak) UIView *containerView2;
@property (nonatomic, weak) UILabel *dateLabel;
@property (nonatomic, strong) NSMutableDictionary *dict;

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dayPlanArray;
@property (nonatomic, strong) NSMutableArray *countArray;

@property (nonatomic, weak) UIView *line;
@property (nonatomic, weak) UIView *cover;
@property (nonatomic, weak) UIView *backgroundView;
@property (nonatomic, assign) NSUInteger count;

/**OA用户名*/
@property (nonatomic, copy) NSString *oaUserName;
/**OA 登陆密码*/
@property (nonatomic, copy) NSString *oaPwd;
/**OA userId*/
@property (nonatomic, copy) NSString *oaUserId;
/**OA 公司ID*/
@property (nonatomic, copy) NSString *oaCompanyID;
@property (nonatomic, assign) NSInteger badgeNumber;
@property (nonatomic, weak) KMDatePicker *datePick;

@end

@implementation WZDayPlanController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupNavItem];
    
    [self getScheduleOfCurrentMonthWithStartDate:[NSDate date]];
    
    [self setupCalendar];
    
    [self getScheduleOfCurrentWithStartDate:[NSDate date]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notice:) name:@"dateOpition" object:nil];
}

- (void)setupNavItem {
    
    [self getUserInfo];
    
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    // 添加导航栏按钮
    self.navigationItem.title = @"日程";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"btn-more" title:nil target:self sel:@selector(addScheduleBtnDidclick:) titleFont:Font10 titleColor:WhiteColor];
    self.view.backgroundColor = WhiteColor;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.calendar reloadData];
}


- (void)getUserInfo {
    
    // 获取OA账户信息
    self.oaUserName = [[USER_DEFAULT objectForKey:@"oaUserName"] stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
    self.oaUserId = [USER_DEFAULT objectForKey:@"oaUserId"];
    self.oaPwd = [[USER_DEFAULT objectForKey:@"oaPwd"] md5String];
    self.oaCompanyID = [USER_DEFAULT objectForKey:@"oaCompanyID"];

//    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
//    self.acc = acc;
//    self.curAccount = [[[CContactMgr alloc] init] loadContactWithUserCode:acc.userName];
}

- (void)setupUI {
    
    // 创建日历对象并且初始化
//    VRGCalendarView *calendar = [[VRGCalendarView alloc] initwithSchedule:self.countArray.copy];
//    calendar.delegate = self;
//    calendar.frame = CGRectMake(0, 0, calendar.width, calendar.height);
//    [self setWeekDayTitle];
//    [self.view addSubview:calendar];
    
//    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(calendar.frame), HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - calendar.calendarHeight - calendar.y);
//    self.tableView.backgroundColor = WhiteColor;
//    [self.view addSubview:self.tableView];
    
    [self setupDatePickerView];
}

- (void)setupDatePickerView {
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect = CGRectMake(0.0, rect.size.height, rect.size.width, 216.0);
    KMDatePicker *datePick = [[KMDatePicker alloc] initWithFrame:rect delegate:self datePickerStyle:KMDatePickerStyleYearMonthDay];
    self.datePick = datePick;
    [self.view addSubview:datePick];
    [self.view bringSubviewToFront:datePick];
}


#pragma mark - 加载当天日程

- (void)getScheduleOfCurrentWithStartDate:(NSDate *)startDate {
    
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    
    [dateComponents setYear:startDate.year];
    [dateComponents setMonth:startDate.month];
    [dateComponents setDay:startDate.day];
    [dateComponents setHour:0];
    [dateComponents setMinute:0];
    
    NSDate *timeDate = [calendar dateFromComponents:dateComponents];
    NSDate *end = [timeDate dateByAddingTimeInterval:24 * 3600 - 1];
    
    NSString *beginTime = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:startDate] * 1000 ];
    
    NSString *endTime = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:end] * 1000];
    
    
    [NetWorkShare queryScheduleWithUserName:self.oaUserName pwd:self.oaPwd beginTime:beginTime endTime:endTime alertBeginTime:nil alertEndTime:nil successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                [self.dayPlanArray removeAllObjects];
                self.dayPlanArray = [WZDayPlan objectArrayWithKeyValuesArray:responseObject[@"rows"]];
                
                [self.dayPlanArray sortUsingComparator:^NSComparisonResult(WZDayPlan *obj1, WZDayPlan *obj2) {
                    
                    return [obj2.typeFlag compare:obj1.typeFlag];
                }];
                
                [self.dayPlanArray sortUsingComparator:^NSComparisonResult(WZDayPlan *obj1, WZDayPlan *obj2) {
                    
                    return [obj1.createTime compare:obj2.createTime];
                }];
                
//                self.count = self.dayPlanArray.count;
                
                
                /*
                
                [self.dayPlanArray enumerateObjectsUsingBlock:^(WZDayPlan *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    
                    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
                    for (UILocalNotification *localNotification in localNotifications) {
                        
                        if (!localNotification.userInfo[LocalNotification_Userinfo_KEY] && [obj.typeFlag isEqualToString:@"1"]) {
                            
                            self.badgeNumber++;
                            
                            NSTimeInterval localNotifyTime = ([obj.startTime longLongValue] + 15 * 60 * 100) / 1000;
                            
                            [[UIApplication sharedApplication] cancelAllLocalNotifications];
                            
                            UILocalNotification *localNotif = [[UILocalNotification alloc] init];
                            localNotif.fireDate = [NSDate dateWithTimeIntervalSince1970:localNotifyTime];
//                            localNotif.repeatInterval = kCFCalendarUnitMinute;
                            localNotif.soundName = UILocalNotificationDefaultSoundName;
                            localNotif.alertAction = @"打开";
                            localNotif.alertTitle = @"未经过编辑的日程提醒";
                            localNotif.alertBody = [NSString stringWithFormat:@"日程提醒:%@", obj.title];
                            
                            NSDictionary *userDict = [NSDictionary dictionaryWithObject:obj.title forKey:LocalNotification_Userinfo_KEY];
                            localNotif.userInfo = userDict;
                            
                            localNotif.applicationIconBadgeNumber = self.badgeNumber;
                            
                            [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
                            
                        } else {
                            
                            // 加入到本地通知中的
                            WZLog(@"日程来源是任务或者已经添加了本地通知的");
                        }
                    }
                    
                }];
                
                */
                
                // 缓存本地数据
                [self.dayPlan.users addObject:self.dayPlanArray];
                
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationBottom];
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:UNKNOWNERROR];
        }
        WZLog(@"chenggong = %@", responseObject);
        
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:NETWORKNERROR];
//        WZLog(@"error = %@",error);
    }];
}


#pragma mark - 获取当月日程数量

- (void)getScheduleOfCurrentMonthWithStartDate:(NSDate *)startDate {
    
    NSCalendar *greCalendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:[NSDate date]];
    [components setYear:startDate.year];
    [components setMonth:startDate.month];
    [components setDay:1];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    
    NSDate *beginTime = [greCalendar dateFromComponents:components];
    NSString *monthBegin = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:beginTime] * 1000];
    NSRange range = [greCalendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    NSDate *endTime = [beginTime dateByAddingTimeInterval:range.length * 24 * 3600 - 1];
    NSString *monthEnd = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:endTime] * 1000];
    
    [NetWorkShare queryScheduleWithUserName:self.oaUserName pwd:self.oaPwd beginTime:monthBegin endTime:monthEnd alertBeginTime:nil alertEndTime:nil successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([[responseObject objectForKey:@"success"] boolValue]) {
//            NSData *responseData = [NSJSONSerialization dataWithJSONObject:responseObject[@"rows"] options:0 error:nil];
//            
//            NSString *json = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//            WZLog(@"json = %@", json);
            
            [MBProgressHUD hideHUDForView:self.view];
            [self.countArray removeAllObjects];
            self.countArray = [WZScheduleList objectArrayWithKeyValuesArray:responseObject[@"rows"]];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            self.dict = dict;
            for (WZScheduleList *obj in _countArray) {
                
                NSDate *startTime = [NSDate changeSpToTime:[NSString stringWithFormat:@"%lld", obj.startTime]];
                NSDate *beginDate = [self creatCustomDateWithDate:startTime Day:startTime.day Hour:0 Minute:0];
                NSDate *endDate = [self creatCustomDateWithDate:startTime Day:startTime.day Hour:23 Minute:59];
                
                
                // 将日期的
                if (obj.startTime) {
                    
                    // 将时间转化为NSDate
                    NSDate *date = [NSDate changeSpToTime:[NSString stringWithFormat:@"%lld", obj.startTime]];
                    NSString *scheduleDate = [NSDate datestrFromDate:date withDateFormat:@"yyyy-MM-dd"];
                    
                    [dict setObject:scheduleDate forKey:date];
                }
                
                
//                if (startTime.day != grifDate.day) {
//                    _count = -1;
//                }
                
//                if (startTime.day == beginDate.day && startTime.day == endDate.day) {
//                    _count++;
//                } else {
//                    
//                    _count = 0;
//                }
//                
//                [dict setObject:@(_count) forKey:startTime];
            }
//            [self setupUI];
            
            
        } else {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:[responseObject objectForKey:@"message"] toView:self.view];
        }
        
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:NETWORKNERROR toView:self.view];
    }];
    
}


// 获取指定时间点
- (NSDate *)creatCustomDateWithDate:(NSDate *)date Day:(NSInteger)day Hour:(NSInteger)hour Minute:(NSInteger)minute  {
    
    NSCalendar *greCalendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
    [components setYear:date.year];
    [components setMonth:date.month];
    [components setDay:day];
    [components setHour:hour];
    [components setMinute:minute];
    
    NSDate *date1 = [greCalendar dateFromComponents:components];
    
//    NSDate *endDate = [beginDate dateByAddingTimeInterval:24 * 3600 - 1];
    
    return date1;
}

// 计算每月有几天
- (void)calculateDaysInTheMonthWithCurrentDate:(NSDate *)currentDate {
    
    
}


/**NSString2TimeStamp */
//将yyyy-MM-dd HH:mm:ss格式时间转换成时间戳
+ (long)changeTimeToTimeSp:(NSString *)timeStr {
    long time;
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromdate=[format dateFromString:timeStr];
    time= (long)[fromdate timeIntervalSince1970];
    //    NSLog(@"%ld",time);
    return time;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.cover removeFromSuperview];
}


#pragma mark - Edit cell

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WZDayPlan *schedule = self.dayPlanArray[indexPath.row];
    
    return ![schedule.typeFlag isEqualToString:@"2"] ? YES : NO;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:DayPlan_DeleteSchedule_Remind];
    
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            [NetWorkShare deleteByIDWithUserName:self.oaUserName pwd:self.oaPwd scheduleID:[self.dayPlanArray[indexPath.row] scheduleID] successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
                if (responseObject) {
                    
                    if ([[responseObject objectForKey:@"success"] boolValue]) {
                        // 移除数据源中的数据
                        [_dayPlanArray removeObjectAtIndex:indexPath.row];
                        
                        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
                        [MBProgressHUD showSuccess:@"删除日程成功"];
                    } else {
                        [MBProgressHUD showMessage:[responseObject objectForKey:@"message"]];
                    }
                } else {
                    [MBProgressHUD showError:UNKNOWNERROR];
                }
            } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                [MBProgressHUD showMessage:NETWORKNERROR];
                WZLog(@"error = %@", error);
            }];

        }];
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            
            
        }];
        
        [alert show];
    }
}


#pragma mark - 添加日程按钮
- (void)addScheduleBtnDidclick:(UIButton *)btn {
    
//    WZAddScheduleController *addScheduleVC = [[WZAddScheduleController alloc] init];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZAddSchedule" bundle:nil];
    WZAddScheduleController *addScheduleVC = [storyboard instantiateViewControllerWithIdentifier:@"AddSchedule"];
    addScheduleVC.oaUserName = self.oaUserName;
    addScheduleVC.oaPwd = self.oaPwd;
    addScheduleVC.block = ^(WZDayPlan *newSchedule){
        
        [self.dayPlanArray insertObject:newSchedule atIndex:0];
        
        [self getScheduleOfCurrentWithStartDate:[NSDate date]];
        
        [self.tableView reloadData];
    };
    
    /**使用代理传值*/
//    addScheduleVC.delegate = self;
    
    // modal 出控制器
//    WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:addScheduleVC];
//    [self.navigationController presentViewController:nav animated:YES completion:nil];
    
    [self.navigationController pushViewController:addScheduleVC animated:YES];
}

#pragma mark - addSchedule的代理方法
- (void)addScheduleController:(WZAddScheduleController *)addScheduleVc didSaveButtonWith:(WZDayPlan *)dayPlan {
    
    [self.dayPlanArray insertObject:dayPlan atIndex:0];
    WZLog(@"chuandi = %@- %@", dayPlan.title, dayPlan.scheduleID);
    
    [self.tableView reloadData];
}


#pragma mark - TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dayPlanArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WZDayPlanCell *cell = [WZDayPlanCell dayPlanCellWithTableView:tableView];
    cell.dayPlay = self.dayPlanArray[indexPath.row];
    return cell;
}


#pragma mark - tableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    [self.tableView reloadData];
//    WZDetailSceduleController *detailVc = [[WZDetailSceduleController alloc] init];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"WZDetailSchedule" bundle:nil];
    WZDetailSceduleController *detailVc = [storyboard instantiateViewControllerWithIdentifier:@"detail"];
    
    NSString *scheduleId = [self.dayPlanArray[indexPath.row] scheduleID];
    detailVc.scheduleID = scheduleId;
    detailVc.oaUserName = self.oaUserName;
    detailVc.oaPwd = self.oaPwd;
    
    WZLog(@"scheduleID = %@", scheduleId);
    WZLog(@"curr = %ld", (long)indexPath.row);
    
    [self.navigationController pushViewController:detailVc animated:YES];
}



#pragma mark 日历Delegate
- (void)calendarView:(VRGCalendarView *)calendarView dateSelected:(NSDate *)date
{
    WZLog(@"=calendarView = %@ - date=%@",calendarView, date);
    
    
    [self getScheduleOfCurrentWithStartDate:date];
}


#pragma mark - 滑动切换日历

- (void)calendarView:(VRGCalendarView *)calendarView switchedToMonthWithTargetHeight:(float)targetHeight animated:(BOOL)animated
{
    
   self.tableView.frame = CGRectMake(0, targetHeight, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - targetHeight);
    
}


#pragma mark - 日历日期选择

- (void)calendarView:(VRGCalendarView *)calendarView dateOptionBtnDidClick:(UIButton *)todayBtn {
    
    [UIView animateWithDuration:.25 animations:^{
        self.datePick.y = self.view.height - 216;
    }];
}


#pragma mark - 点击今天按钮

- (void)calendarView:(LBCalendar *)calendarView todayBtnDidClick:(UIButton *)todayBtn {
    
//    todayBtn.selected = !todayBtn.selected;
//    if (!todayBtn.selected) {
//        
////        self.count = 0;
//        self.tableView.dataSource = nil;
//        [self.tableView reloadData];
//        
//    } else {
//        
////        self.count = self.dayPlanArray.count;
//        self.tableView.dataSource = self;
//        [self.tableView reloadData];
//    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"dateOpition" object:nil];
    
    [self getScheduleOfCurrentWithStartDate:[NSDate date]];
}

- (void)notice:(NSNotification *)notice {
    
    
}

#pragma mark - 日期选择器代理

- (void)datePicker:(KMDatePicker *)datePicker didSelectDate:(KMDatePickerDateModel *)datePickerDate {
    
    //TODO: 切换日历, 加载日程数据
    WZLog(@"日期选择器选择了日期");
    NSString *dateStr = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",
                         datePickerDate.year,
                         datePickerDate.month,
                         datePickerDate.day,
                         datePickerDate.hour,
                         datePickerDate.minute
                         ];
    
    NSDate *date = [NSDate dateFromString:dateStr format:@"yyyy-MM-dd HH:mm:ss"];
    [self getScheduleOfCurrentWithStartDate:date];
}

- (void)datePicker:(KMDatePicker *)datePicker cancelBtnDidClick:(KMDatePickerDateModel *)datePickerDate {
    
    [UIView animateWithDuration:.25 animations:^{
        
        datePicker.y = self.view.height;
        
    }];
}


//- (void)datePicker:(KMDatePicker *)datePicker confirmBtnDidClick:(KMDatePickerDateModel *)datePickerDate {
//    
//    //TODO: 切换日历, 刷新数据
//    WZLog(@"点击了确定按钮");
//    
//    
//    [self datePicker:datePicker cancelBtnDidClick:datePickerDate];
//}


#pragma mark - 初始化日历

- (void)setupCalendar {
    
    [self createCalendarheaderView];
    [self createBGScrollview];
    calendarContentView = [[LBCalendarContentView alloc]initWithFrame:CGRectMake(0, KCalendar_Spacing, self.view.frame.size.width, KCalendar_contentView_Height)];
    [BGScrollview addSubview:calendarContentView];
    
    LBCalendar *calendar = [LBCalendar new];
    self.calendar = calendar;
    
    self.calendar.calendarAppearance.calendar.firstWeekday = 2; // Sunday == 1, Saturday == 7
    self.calendar.calendarAppearance.dayRectangularRatio = 9. / 10.;
    
    [self.calendar setContentView:calendarContentView];
    [self.calendar setDataSource:self];
    
    [self creatCalendarTitleView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateym:) name:@"currentYearMonth" object:nil];
    
//    UITapGestureRecognizer * TapGesturRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureRecognizer)];
    
//    [self.view addGestureRecognizer:TapGesturRecognizer ];
    
    //    dateDetailView = [[DateDetailView alloc]initWithFrame:CGRectMake(0, calendarContentView.frame.size.height+10, self.view.frame.size.width, BGScrollview.frame.size.height-calendarContentView.frame.size.height-10)];
    
    [self creatContainerView2];
    
}


#pragma mark - 日历标题视图

- (void)creatCalendarTitleView {
    
    NSDate *defaultDate = [[NSDate alloc]init];
    defaultDate = self.calendar.currentDate;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy年MM月"];
    NSString *defaultDateStr = [dateFormatter stringFromDate:defaultDate];
    
    CGRect rect1 = CGRectMake(0, 0, KScreen_width, KCalendar_TitleView_Height);;
    UIView *calendarTitleView = [[UIView alloc] initWithFrame:rect1];
//    calendarTitleView.backgroundColor = [UIColor redColor];
    [self.view addSubview:calendarTitleView];
    
    UIImageView *todayView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"today"]];
    CGRect rect = todayView.frame;
    UIButton *todayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    todayBtn.adjustsImageWhenHighlighted = NO;
    [calendarTitleView addSubview:todayBtn];
    todayBtn.frame = rect;
    [todayBtn setBackgroundImage:[UIImage imageNamed:@"today"] forState:UIControlStateNormal];
    [todayBtn addTarget:self action:@selector(didGoTodayTouch) forControlEvents:UIControlEventTouchUpInside];
    
    [todayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(calendarTitleView.mas_left).offset(15);
        make.centerY.mas_equalTo(calendarTitleView.mas_centerY);
    }];

    UILabel *dateLabel = [[UILabel alloc] init];
    self.dateLabel = dateLabel;
    [calendarTitleView addSubview:dateLabel];
    dateLabel.textColor = [UIColor blackColor];
    dateLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:19];
    dateLabel.text = defaultDateStr;
    [dateLabel sizeToFit];
    [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(calendarTitleView.mas_centerY);
        make.centerX.equalTo(calendarTitleView.mas_centerX).offset(-10);
    }];
    

    UIButton *optionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    optionBtn.adjustsImageWhenHighlighted = NO;
    [calendarTitleView addSubview:optionBtn];
    [optionBtn setBackgroundImage:[UIImage imageNamed:@"down"] forState:UIControlStateNormal];
    [optionBtn addTarget:self action:@selector(optionDate) forControlEvents:UIControlEventTouchUpInside];
    [optionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(20);
        make.left.equalTo(dateLabel.mas_right).offset(5);
        make.centerY.mas_equalTo(dateLabel.mas_centerY);
    }];
    
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.backgroundColor = [UIColor clearColor];
    rightBtn.adjustsImageWhenHighlighted = NO;
    [rightBtn setImage:[UIImage imageNamed:@"Schedule_Calendar_right"] forState:UIControlStateNormal];
    UITapGestureRecognizer *rightTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightTapGestureRecognizer)];
    [rightBtn addGestureRecognizer:rightTapGesture];

    [calendarTitleView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(30);
        make.right.equalTo(calendarTitleView.mas_right);
        make.centerY.mas_equalTo(calendarTitleView);
    }];
    
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.backgroundColor = [UIColor clearColor];
    leftBtn.adjustsImageWhenHighlighted = NO;
    [leftBtn setImage:[UIImage imageNamed:@"Schedule_Calendar_left"] forState:UIControlStateNormal];
    UITapGestureRecognizer *leftTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftTapGestureRecognizer)];
    [leftBtn addGestureRecognizer:leftTapGesture];
    
    [calendarTitleView addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(30);
        make.right.equalTo(rightBtn.mas_left).offset(-5);
        make.centerY.mas_equalTo(calendarTitleView.mas_centerY);
    }];
    
    /*
    
    UIToolbar *mycustomToolBar;
    NSMutableArray *mycustomButtons = [[NSMutableArray alloc] init];
    UIBarButtonItem *backBt  = [[UIBarButtonItem alloc]
                                initWithTitle:@"返回"
                                style:UIBarButtonItemStylePlain
                                target:self
                                action:@selector(backBtTap)];
    backBt.width = 40;
    
    _SelectionMonthBt = (UIButton *)[[UIBarButtonItem alloc]
                         initWithTitle:defaultDateStr
                         style:UIBarButtonItemStylePlain
                         target:self
                         action:@selector(selectDate)];
    _SelectionMonthBt.width = 40;
    
    UIBarButtonItem *TodayTouchBT = [[UIBarButtonItem alloc]
                                     initWithImage:[UIImage imageNamed:@"today"]
                                     style:UIBarButtonItemStylePlain
                                     target:self
                                     action:@selector(didGoTodayTouch)];
    TodayTouchBT.width = 80;
    
    UIBarButtonItem *MoreBt = [[UIBarButtonItem alloc]
                               initWithTitle:@"更多"
                               style:UIBarButtonItemStylePlain
                               target:self
                               action:@selector(moreBtTap)];
    MoreBt.width = 40;
    
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    mycustomButtons = [NSMutableArray arrayWithObjects: TodayTouchBT, spaceItem, _SelectionMonthBt, spaceItem, MoreBt, spaceItem, backBt, nil];
    
    mycustomToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f,self.view.frame.size.width, 44)];
    mycustomToolBar.barStyle = UIBarStyleDefault;
    [mycustomToolBar setItems:mycustomButtons animated:YES];
    [mycustomToolBar sizeToFit];
    mycustomToolBar.tintColor = [UIColor colorWithRed:252 / 255.0 green:246 / 255.0 blue:244 / 255.0 alpha:1.0];
    
    // 背景颜色
    mycustomToolBar.barTintColor = [UIColor whiteColor];
    
    // 按钮的颜色
    mycustomToolBar.tintColor = [UIColor clearColor];
//    [mycustomToolBar setBackgroundImage:[UIImage imageNamed:@"Transparent.png"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];//设置ToolBar 为透明
    //    toolBarHairlineImageView = [self findHairlineImageViewtop:mycustomToolBar];
    
//    [self.view addSubview:mycustomToolBar];
    
//    [titleView addSubview:TodayTouchBT];
     
    */
}


#pragma mark - 日历周视图

- (void)createCalendarheaderView{
    
    CGFloat itemW  = self.view.frame.size.width / 7;
    
    //    NSArray *array = @[@"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@"周日"];
    NSArray *array = @[@"一", @"二", @"三", @"四", @"五", @"六",@"日"];
    UIView *weekBg = [[UIView alloc] init];
    weekBg.backgroundColor = [UIColor colorWithRed:252 / 255.0 green:246 / 255.0 blue:244 / 255.0 alpha:1.0];
    weekBg.frame = CGRectMake(0, KCalendar_TitleView_Height, self.view.frame.size.width, KCalendar_WeekDayView_Height);
    [self.view addSubview:weekBg];
    
    for (int i = 0; i < 7; i++) {
        UILabel *week = [[UILabel alloc] init];
        week.text     = array[i];
        week.font     = [UIFont systemFontOfSize:14];
        week.frame    = CGRectMake(itemW * i, 6, itemW, 32);
        week.textAlignment   = NSTextAlignmentCenter;
        week.backgroundColor = [UIColor clearColor];
        week.textColor = !(i == 5 || i == 6) ? [UIColor blackColor] : [UIColor redColor];
        [weekBg addSubview:week];
    }
    
}

#pragma mark - 日历滚动试图

- (void)createBGScrollview{
    
    BGScrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, KCalendar_TitleView_Height + KCalendar_WeekDayView_Height, self.view.frame.size.width, self.view.frame.size.height - KCalendar_TitleView_Height - KCalendar_WeekDayView_Height)];
    BGScrollview.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
//    BGScrollview.backgroundColor = [UIColor redColor];
    BGScrollview.pagingEnabled = YES;
    BGScrollview.showsVerticalScrollIndicator = NO;
    BGScrollview.delegate = self;
//    BGScrollview.alwaysBounceVertical = NO;
//    BGScrollview.alwaysBounceHorizontal = NO;
    [self.view addSubview:BGScrollview];
}


#pragma mark - 日程视图

- (void)creatContainerView2 {
    
    CGRect rect1 = CGRectMake(0, calendarContentView.frame.size.height, self.view.frame.size.width, KScreen_Height - calendarContentView.height);
    UIView *containerView2 = [[UIView alloc] initWithFrame:rect1];
    self.containerView2 = containerView2;
//    containerView2.backgroundColor = [UIColor greenColor];
    [BGScrollview addSubview:containerView2];
    
    CGRect rect2 = CGRectMake(0, 0, self.view.frame.size.width, KCalendar_WeekDayView_Height);
    UIView *changeView = [[UIView alloc] initWithFrame:rect2];
    self.changeView = changeView;
//    changeView.backgroundColor = [UIColor purpleColor];
    [self.containerView2 addSubview:changeView];

    CGRect lineRect1 = CGRectMake(0, 0, KScreen_width, 0.5);
    UIView *topLine = [[UIView alloc] initWithFrame:lineRect1];
    topLine.backgroundColor = [UIColor grayColor];
    [changeView addSubview:topLine];
//    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(changeView);
//        make.width.mas_equalTo(changeView);
//        make.height.mas_equalTo(1);
//    }];
    
    CGRect lineRect2 = CGRectMake(0, KCalendar_WeekDayView_Height - 0.5, KScreen_width, 0.5);
    UIView *bottomLine = [[UIView alloc] initWithFrame:lineRect2];
    bottomLine.backgroundColor = [UIColor grayColor];
    [changeView addSubview:bottomLine];
//    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(changeView);
//        make.width.mas_equalTo(changeView);
//        make.height.mas_equalTo(1);
//    }];
    
    UIButton *changeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.changeButton = changeButton;
    [changeButton setImage:[UIImage imageNamed:@"button-up"] forState:UIControlStateNormal];
    [changeButton setImage:[UIImage imageNamed:@"button-down"] forState:UIControlStateSelected];
    [changeButton addTarget:self action:@selector(didChangeModeToBGScrollviewuch:) forControlEvents:UIControlEventTouchUpInside];
    [changeView addSubview:changeButton];
    [changeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(changeView);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(changeView);
    }];

    
    CGRect tableRect = CGRectMake(0, KCalendar_WeekDayView_Height, KScreen_width, containerView2.height - KCalendar_ChangeView_Height);
    UITableView *tableView = [[UITableView alloc] initWithFrame:tableRect style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [containerView2 addSubview:self.tableView];
    
}

#pragma mark - Buttons callback
#pragma mark - 按钮回调

- (void)backBtTap {
    
    [dsView cancelBtTap];
}

- (void)moreBtTap {
    
    [dsView cancelBtTap];
}


-(void)changAlpha: (float )BGAlpha {
    
    BGScrollview.alpha = BGAlpha;
    BGScrollview.userInteractionEnabled=YES;
}

- (void)didTouchDatePickeOKBt:(NSDate *)date1 {
    
    [self.calendar setCurrentDate:date1];
    [dsView cancelBtTap];
    
}

- (void)updateym:(NSNotification *)notification {
    
    _dateLabel.text = [notification object];
}


- (void)optionDate {
    
    if (!dsView) {
        dsView = [[DateSelectView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 270)];
        
        dsView.delegate = self;
        
        BGScrollview.userInteractionEnabled=YES;
        
        [UIView animateWithDuration:.6 animations:^{
            dsView.frame = CGRectMake(0, self.view.frame.size.height-270, self.view.frame.size.width, 270);
            
            [self.view addSubview:dsView];
            
            BGScrollview.alpha = 0.4;
            
        } completion:^(BOOL finished) {
            ///////////
            
        }];
    }else{
        
        BGScrollview.userInteractionEnabled=YES;
        [UIView animateWithDuration:.6 animations:^{
            [self.view addSubview:dsView];
            dsView.frame = CGRectMake(0, self.view.frame.size.height-270, self.view.frame.size.width, 270);
            BGScrollview.alpha = 0.4;
            
        } completion:^(BOOL finished) {
            //////////
            
        }];
        
    }
    
}


- (void)rightTapGestureRecognizer {
    
    WZLog(@"右边手势");
    [self.calendar loadNextMonth];
}


- (void)leftTapGestureRecognizer {
   
    WZLog(@"左边手势");
    [self.calendar loadPreviousMonth];
}


- (void)tapGestureRecognizer {
    
    [dsView cancelBtTap];
}


- (void)didGoTodayTouch {
    if (dsView) {
        [dsView cancelBtTap];
    }
    [self.calendar setCurrentDate:[NSDate date]];
    
    [self getScheduleOfCurrentWithStartDate:[NSDate date]];
}

- (void)changeModelBtnDidClick {
    
    WZLog(@"changed");
}


- (void)didChangeModeToBGScrollviewuch:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.calendar.calendarAppearance.isWeekMode = !self.calendar.calendarAppearance.isWeekMode;
    [self transitionExample];
}


/*
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if(!self.calendar.calendarAppearance.isWeekMode){
        if (BGScrollview.contentOffset.y >=10) {
            self.calendar.calendarAppearance.isWeekMode = !self.calendar.calendarAppearance.isWeekMode;
            [self transitionExample];
        }
    }
    else{
        if (BGScrollview.contentOffset.y <=-10) {
            self.calendar.calendarAppearance.isWeekMode = !self.calendar.calendarAppearance.isWeekMode;
            [self transitionExample];
            
        }
        
    }
    [BGScrollview setContentOffset:CGPointMake(0, 0)];
    
} */



#pragma mark - LBCalendarDataSource

- (BOOL)calendarHaveEvent:(LBCalendar *)calendar date:(NSDate *)date
{
    
    /*
    __block BOOL hasSchedule = NO;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 将NSDate 转化为Nsstring
        NSString *str = [NSDate datestrFromDate:date withDateFormat:@"yyyy-MM-dd"];
        // 根据value获取key
        NSArray *dateStr = [self.dict allValues];
        
        for (NSString *scheduleDate in dateStr) {
            WZLog(@"date = %@", str);
            
            WZLog(@"dateStr = %@", scheduleDate);
            
            if (![scheduleDate isEqualToString:str]) {
                hasSchedule = NO;
                continue;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                hasSchedule = YES;
            });
        }
    });
    
    return hasSchedule;
*/
    
    /*
    // 将NSDate 转化为Nsstring
    NSString *str = [NSDate datestrFromDate:date withDateFormat:@"yyyy-MM-dd"];
    // 根据value获取key
    NSArray *dateStr = [self.dict allValues];
    
    for (NSString *scheduleDate in dateStr) {
        WZLog(@"date = %@", str);
        
        WZLog(@"dateStr = %@", scheduleDate);
        
        if (![scheduleDate isEqualToString:str]) {
            continue;
        }
        
        return YES;
        break;
    }
    return nil;
    */
    
    return (rand() % 10) == 1;
    
}

- (void)calendarDidDateSelected:(LBCalendar *)calendar date:(NSDate *)date
{
    WZLog(@"selectDate : =  %@", date);
    [self getScheduleOfCurrentWithStartDate:date];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DaySelected" object:date];
}


#pragma mark - Transition examples

- (void)transitionExample
{
    CGFloat newHeight = 300;
    if(self.calendar.calendarAppearance.isWeekMode){
        newHeight = 50.0;
    }
    
    [UIView animateWithDuration:.5
                     animations:^{
                         
                         calendarContentView.frame = CGRectMake(0, 5, self.view.frame.size.width, newHeight);
                         _containerView2.frame = CGRectMake(0, newHeight+10, self.view.frame.size.width, BGScrollview.frame.size.height-newHeight-10);
                         _tableView.frame = CGRectMake(0, KCalendar_ChangeView_Height, self.view.frame.size.width, _containerView2.height - KCalendar_ChangeView_Height);
                         [self.view layoutIfNeeded];
                     }];
    
    [UIView animateWithDuration:.25
                     animations:^{
                         
                         calendarContentView.layer.opacity = 0;
                     }
                     completion:^(BOOL finished) {
                         [self.calendar reloadAppearance];
                         
                         [UIView animateWithDuration:.25
                                          animations:^{
                                              calendarContentView.layer.opacity = 1;
                                          }];
                     }];
}


// 添加日历按钮
- (void)addCalendarBtnWithImage:(NSString *)norImage SeleImage:(NSString *)seleImage Frame:(CGRect)btnFrame Target:(SEL)target {
    
    UIButton *btn = [[UIButton alloc] initWithFrame:btnFrame];
    [btn setImage:[UIImage imageNamed:norImage] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:seleImage] forState:UIControlStateSelected];
    [btn addTarget:self action:target forControlEvents:UIControlEventTouchUpInside];
    btn.adjustsImageWhenHighlighted = NO;
    [self.view addSubview:btn];
}



// 懒加载
- (NSMutableArray *)dayPlanArray {
    
    if (_dayPlanArray == nil) {
        _dayPlanArray = [[NSMutableArray alloc] init];
    }
    return _dayPlanArray;
}

- (NSMutableArray *)countArray {
    if (!_countArray) _countArray = [[NSMutableArray alloc] init];
    return _countArray;
}


@end
